package com.audaque.springboot.foshanupload.web.websocketdemo.decoder;


import javax.websocket.DecodeException;
import javax.websocket.Decoder;
import javax.websocket.EndpointConfig;


import com.audaque.springboot.foshanupload.web.websocketdemo.model.req.MessageReq;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;

public class JsonDecoder  implements Decoder.Text<MessageReq> {
    @Autowired
    private ObjectMapper objectMapper;
    @Override//Initialization does nothing
    public void init(EndpointConfig config) {}

    @Override//Judgment of whether decoding is possible
    public boolean willDecode(String text) {
        return (text != null);
    }

    @Override//Decoding process(JSON → object)
    public MessageReq decode(String text) throws DecodeException {

        MessageReq obj = null;
        try {
            obj = objectMapper.readValue(text, MessageReq.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return obj;
    }

    @Override//Do nothing to destroy
    public void destroy() {}
}
